﻿using _111.Models;
using Dapper;
using Microsoft.Extensions.Logging;
using MyDapperApi.Models;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using QYWXUpdate.DataModel;
using System.Data;
using System.Text;
using static MyDapperApi.Services.DateBaseService;

namespace MyDapperApi.Services;

public class NetUpdateService : INetUpdateService
{
    private readonly IConfiguration _configuration;
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly IDateBaseService _dateBaseService;

    // 通过依赖注入获取配置，从而读取连接字符串
    public NetUpdateService(IHttpClientFactory httpClientFactory,
        IConfiguration configuration,
        IDateBaseService dateBaseService)
    {
        _configuration = configuration;
        _httpClientFactory = httpClientFactory;
        _dateBaseService = dateBaseService;
    }

    /// <summary>
    /// 数据流转String
    /// </summary>
    /// <param name="stream"></param>
    /// <returns></returns>
    public async Task<string> StreamToStringAsync(Stream stream)
    {
        if (stream.CanSeek)
        {
            stream.Seek(0, SeekOrigin.Begin);
        }

        using (StreamReader reader = new StreamReader(stream))
        {
            return await reader.ReadToEndAsync();
        }
    }

    /// <summary>
    /// 获取企业微信token标准方法
    /// </summary>
    /// <param name="corpId"></param>
    /// <param name="secret"></param>
    /// <returns></returns>
    public async Task<string> GetAccessTokenAsync(string corpId, string secret)
    {

        var Secret = AesCbcHelper.Encrypt(secret, System.Text.Encoding.Default.GetBytes("xshAesKey1234567"), System.Text.Encoding.Default.GetBytes("1234567890abcdef"));

        var content = new
        {
            mode = "qywxupdate",
            corpId = corpId,
            secret = Secret
        };

        var client = _httpClientFactory.CreateClient();
        client.DefaultRequestHeaders.Add("ContentType", "application/json");

        var postContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://ziyan.xshhotels.cn:8687/qwApi/getToken", postContent);


        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                var result = JsonConvert.DeserializeObject<TokenResponse>(res);
                if (result != null && result.code == 200)
                {
                    return result.body;
                }
            }

        }
        return "";
    }

    /// <summary>
    /// 企业微信推送自定义功能标准方法...
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateUserWorkbenchDataAsync(QywxUpdateDetail request)
    {
        var result = new CommonResponse();
        var token = await GetAccessTokenAsync(request.CorpId, request.Secret);
        var client = _httpClientFactory.CreateClient();

        var temp = JsonConvert.SerializeObject(request.Content);

        var content = new StringContent(
            JsonConvert.SerializeObject(request.Content),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = new HttpResponseMessage();

        if (request.UseridList?.Any(id => !string.IsNullOrEmpty(id)) == true)
        {
            response = await client.PostAsync(
            $"https://qyapi.weixin.qq.com/cgi-bin/agent/batch_set_workbench_data?access_token={token}",
            content);
        }
        else
        {
            response = await client.PostAsync(
            $"https://qyapi.weixin.qq.com/cgi-bin/agent/set_workbench_template?access_token={token}",
            content);
        }

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<WXResponse>(res);
                if (wxRespon != null && wxRespon.errmsg == "ok")
                {
                    result.SetSuccess();
                }
                else
                {
                    result.SetError();
                    result.msg = res;
                }
                return result;
            }

        }
        result.SetError();
        result.msg = "与微信服务器交互失败";
        response.EnsureSuccessStatusCode();
        return result;
    }

    /// <summary>
    /// 企业微信推送自定义功能标准方法
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> GetUserIdByCorpToken()
    {
        var result = new CommonResponse();
        var token = await GetAccessTokenAsync("ww41ce2a97523f4d1a", "gm0eUp5pNnuafpyRP8DsPNzuDJJx3J5omO53ervov2E");
        var client = _httpClientFactory.CreateClient();

        var cont = new
        {
            cursor = "",
            limit = 1000
        };

        var content = new StringContent(
            JsonConvert.SerializeObject(cont),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = new HttpResponseMessage();

        response = await client.PostAsync(
        $"https://qyapi.weixin.qq.com/cgi-bin/user/list_id?access_token={token}",
        content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<WXUserListResponse>(res);
                if (wxRespon != null && wxRespon.errmsg == "ok")
                {
                    result.SetSuccess();
                }
                else
                {
                    result.SetError();
                    result.msg = res;
                }
                return result;
            }

        }
        result.SetError();
        result.msg = "与微信服务器交互失败";
        response.EnsureSuccessStatusCode();
        return result;
    }

    /// <summary>
    /// 企业微信获取数据接口
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> GetUserWorkbenchDataAsync(QywxUpdateDetail request)
    {
        var result = new CommonResponse();
        var token = await GetAccessTokenAsync(request.CorpId, request.Secret);
        var client = _httpClientFactory.CreateClient();

        request.Content = new
        {
            agentid = request.AgentId,
        };

        var temp = JsonConvert.SerializeObject(request.Content);

        var content = new StringContent(
            JsonConvert.SerializeObject(request.Content),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = await client.PostAsync(
            $"https://qyapi.weixin.qq.com/cgi-bin/agent/get_workbench_template?access_token={token}",
            content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                result.msg = res;
                //var wxRespon = JsonConvert.DeserializeObject<QywxGetModel>(res);
                //if (wxRespon != null && wxRespon.errmsg == "ok")
                //{
                //    result.SetSuccess();
                //}
                //else
                //{
                //    result.SetError();
                //    result.msg = res;
                //}
                return result;
            }

        }
        result.SetError();
        result.msg = "与微信服务器交互失败";
        response.EnsureSuccessStatusCode();
        return result;
    }

    public async Task<CommonResponse> GetDetail(IdRequest request)
    {
        var result = new CommonResponse();
        var qywxRequest = new QywxUpdateDetail()
        {
            AgentId = request.Id,
            CorpId = "ww41ce2a97523f4d1a",
            Secret = GetSecret(request.Id)
        };
        result = await GetUserWorkbenchDataAsync(qywxRequest);
        return result;
    }
    // 获取数据库连接
    private IDbConnection CreateConnection()
    {
        return new MySqlConnection(_configuration.GetConnectionString("DefaultConnection"));
    }

    public async Task<IEnumerable<KeyDetailEntity>> GetAllUsers()
    {
        using var connection = CreateConnection();
        var sql = "SELECT * FROM key_detail";
        return await connection.QueryAsync<KeyDetailEntity>(sql);
    }

    /// <summary>
    /// 更新数据从数据库
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateKeyData()
    {
        var result = new CommonResponse();
        using var connection = CreateConnection();
        var sql = "SELECT * FROM key_detail";
        var detail = await connection.QueryAsync<KeyDetailEntity>(sql);

        if (detail != null && detail.ToList().Count > 0)
        {
            var dateModel = new List<KeyDetailModel>();
            foreach (var item in detail.ToList())
            {
                var model = new KeyDetailModel()
                {
                    key = item.Key,
                    data = item.Data,
                    jump_url = item.Jump_Url,
                    pagepath = item.PagePath
                };
                dateModel.Add(model);
            }
            var contentDate = new QywxUpdateDetail();
            contentDate.Content = new
            {
                agentid = "1000157",
                type = "keydata",
                keydata = new
                {
                    items = dateModel
                }
            };
            contentDate.CorpId = "ww41ce2a97523f4d1a";
            contentDate.Secret = "gm0eUp5pNnuafpyRP8DsPNzuDJJx3J5omO53ervov2E";
            await UpdateUserWorkbenchDataAsync(contentDate);
            result.SetSuccess("");
        }
        result.SetError();
        return result;
    }

    public async Task<CommonResponse> UpdateQywx(QywxTotalModel request)
    {
        var result = new CommonResponse();
        switch (request.type)
        {
            case "image":
                var imageDetail = new QywxImageRequest()
                {
                    agentid = request.agentid,
                    type = request.type,
                    image = request.image,
                    userid_list = request.userid_list,
                };
                result = await UpdateImageDataFromApi(imageDetail);
                break;
            case "list":
                var listDetail = new QywxListRequest()
                {
                    agentid = request.agentid,
                    type = request.type,
                    list = request.list,
                    userid_list = request.userid_list,
                };
                result = await UpdateListDataFromApi(listDetail);
                break;
            case "keydata":
                var keydataDetail = new QywxKeyRequest()
                {
                    agentid = request.agentid,
                    type = request.type,
                    keydata = request.keydata,
                    userid_list = request.userid_list,
                };
                result = await UpdateKeyDataFromApi(keydataDetail);
                break;
            case "webview":
                var webviewDetail = new QywxWebViewRequest()
                {
                    agentid = request.agentid,
                    type = request.type,
                    webview = request.webview,
                    userid_list = request.userid_list,
                };
                result = await UpdateWebViewDataFromApi(webviewDetail);
                break;
        }
        return result;
    }

    /// <summary>
    /// 更新图片数据从api
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateImageDataFromApi(QywxImageRequest request)
    {
        var result = new CommonResponse();
        var contentDate = new QywxUpdateDetail();
        if (request.userid_list.Count > 0)
        {
            contentDate.Content = new
            {
                agentid = request.agentid,
                userid_list = request.userid_list,
                data = new
                {
                    type = request.type,
                    image = request.image,
                }
            };
        }
        else
        {
            contentDate.Content = new
            {
                agentid = request.agentid,
                type = request.type,
                image = request.image,
                userid_list = request.userid_list,
            };
        }
        contentDate.CorpId = "ww41ce2a97523f4d1a";
        contentDate.Secret = GetSecret(request.agentid);
        contentDate.UseridList = request.userid_list;
        if (contentDate.Secret == "error")
        {
            result.SetError();
            return result;
        }

        result = await UpdateUserWorkbenchDataAsync(contentDate);

        return result;
    }

    /// <summary>
    /// 更新关键数据从api
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateKeyDataFromApi(QywxKeyRequest request)
    {
        var result = new CommonResponse();
        var contentDate = new QywxUpdateDetail();

        if (request.userid_list.Count > 0)
        {
            contentDate.Content = new
            {
                agentid = request.agentid,
                userid_list = request.userid_list,
                data = new
                {
                    type = request.type,
                    keydata = request.keydata,
                }
            };
        }
        else
        {
            contentDate.Content = new
            {
                agentid = request.agentid,
                type = request.type,
                keydata = request.keydata,
                userid_list = request.userid_list,
            };
        }
        contentDate.CorpId = "ww41ce2a97523f4d1a";
        contentDate.Secret = GetSecret(request.agentid);
        contentDate.UseridList = request.userid_list;
        if (contentDate.Secret == "error")
        {
            result.SetError();
            return result;
        }

        result = await UpdateUserWorkbenchDataAsync(contentDate);

        return result;
    }

    /// <summary>
    /// 更新列表数据从api
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateListDataFromApi(QywxListRequest request)
    {
        var result = new CommonResponse();
        var contentDate = new QywxUpdateDetail();

        contentDate.Content = new
        {
            agentid = request.agentid,
            type = request.type,
            list = request.list,
            userid_list = request.userid_list,
        };
        contentDate.CorpId = "ww41ce2a97523f4d1a";
        contentDate.Secret = GetSecret(request.agentid);
        contentDate.UseridList = request.userid_list;
        if (contentDate.Secret == "error")
        {
            result.SetError();
            return result;
        }

        result = await UpdateUserWorkbenchDataAsync(contentDate);

        return result;
    }

    /// <summary>
    /// 更新网页数据从api
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateWebViewDataFromApi(QywxWebViewRequest request)
    {
        var result = new CommonResponse();
        var contentDate = new QywxUpdateDetail();

        contentDate.Content = new
        {
            agentid = request.agentid,
            type = request.type,
            webview = request.webview,
            userid_list = request.userid_list,
        };
        contentDate.CorpId = "ww41ce2a97523f4d1a";
        contentDate.Secret = GetSecret(request.agentid);
        contentDate.UseridList = request.userid_list;
        if (contentDate.Secret == "error")
        {
            result.SetError();
            return result;
        }

        result = await UpdateUserWorkbenchDataAsync(contentDate);

        return result;
    }

    public string GetSecret(string agentId)
    {
        var result = string.Empty;
        switch (agentId)
        {
            case "1000157"://关键数据型
                result = "gm0eUp5pNnuafpyRP8DsPNzuDJJx3J5omO53ervov2E";
                break;
            case "1000158"://列表型
                result = "MVjl_uZJIzfh2cMRE_S1NMPeC2gXz_GBf0i8ZmZ5t_Q";
                break;
            case "1000161"://图片型
                result = "Y1eyXBj3nBDg1NwZrXmCyMnNyO54xdZkBHUz7draTxE";
                break;
            case "1000173"://图片型
                result = "Ip8TTg8gpHbx_4gOIJphFENjkuLqzLnDaS90TJ4BvNs";
                break;
            default:
                result = "error";
                break;
        }
        return result;
    }

    /// <summary>
    /// 自动更新企业微信通知消息
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateReport()
    {
        var result = new CommonResponse();

        var sql = string.Empty;
        var sqlBuilder = new SqlBuilder();

        sql = @$"select * 
FROM formtable_main_25 
WHERE lcbh != '' 
ORDER BY sqrq desc ";

        sqlBuilder.AddPage(1,3,1);

        var res = await _dateBaseService.QueryAsync<OaReportEntity>(sql,sqlBuilder,1, "OaData");

        var postRes = new QywxTotalModel()
        {
            agentid = "1000158",
            type = "list",
            userid_list = new List<string>(),
            list = new keydataDetail<listItemsDetail>()
        };

        var itemList = new List<listItemsDetail>();

        foreach (var item in res)
        {
            var temp = new listItemsDetail();
            temp.title = item.Wjmc;
            temp.jump_url = "http://oa.xshhotels.com/spa/document/static4mobile/index.html?_random=1757552763031#/news/167628957?moduleid=167628957&1&24d4442ea39243c2b50";
            itemList.Add(temp);
        }

        postRes.list.items = itemList;

        result = await UpdateQywx(postRes);

        return result;
    }
    //iida
}